{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "copyright"
      },
      "outputs": [],
      "source": [
        "# Copyright 2021 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "title:migration,new"
      },
      "source": [
        "# Vertex SDK: Submit a HyperParameter tuning training job with TensorFlow\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_aip"
      },
      "source": [
        "## Installation\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_storage"
      },
      "source": [
        "Install the Google *cloud-storage* library as well.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Y7Y8OgsQRlvq"
      },
      "outputs": [],
      "source": [
        "! pip3 install google-cloud-storage"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "restart"
      },
      "source": [
        "### Restart the Kernel\n",
        "\n",
        "Once you've installed the Vertex SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7LoqmDz3Rlvu"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "if not os.getenv(\"AUTORUN\"):\n",
        "    # Automatically restart kernel after installs\n",
        "    import IPython\n",
        "\n",
        "    app = IPython.Application.instance()\n",
        "    app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "before_you_begin"
      },
      "source": [
        "## Before you begin\n",
        "\n",
        "### GPU run-time\n",
        "\n",
        "*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\n",
        "\n",
        "### Set up your GCP project\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "1. [Select or create a GCP project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
        "\n",
        "2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
        "\n",
        "3. [Enable the Vertex APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\n",
        "\n",
        "4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebooks.\n",
        "\n",
        "5. Enter your project ID in the cell below. Then run the  cell to make sure the\n",
        "Cloud SDK uses the right project for all the commands in this notebook.\n",
        "\n",
        "**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "set_project_id"
      },
      "outputs": [],
      "source": [
        "PROJECT_ID = \"[your-project-id]\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "autoset_project_id"
      },
      "outputs": [],
      "source": [
        "if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
        "    # Get your GCP project id from gcloud\n",
        "    shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
        "    PROJECT_ID = shell_output[0]\n",
        "    print(\"Project ID:\", PROJECT_ID)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "set_gcloud_project_id"
      },
      "outputs": [],
      "source": [
        "! gcloud config set project $PROJECT_ID"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "region"
      },
      "source": [
        "#### Region\n",
        "\n",
        "You can also change the `REGION` variable, which is used for operations\n",
        "throughout the rest of this notebook.  Below are regions supported for Vertex. We recommend when possible, to choose the region closest to you.\n",
        "\n",
        "- Americas: `us-central1`\n",
        "- Europe: `europe-west4`\n",
        "- Asia Pacific: `asia-east1`\n",
        "\n",
        "You cannot use a Multi-Regional Storage bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see [Region support for Vertex services]()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XEwJmlbzRlvy"
      },
      "outputs": [],
      "source": [
        "REGION = \"us-central1\"  # @param {type: \"string\"}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "timestamp"
      },
      "source": [
        "#### Timestamp\n",
        "\n",
        "If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LwF83xbORlvz"
      },
      "outputs": [],
      "source": [
        "from datetime import datetime\n",
        "\n",
        "TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gcp_authenticate"
      },
      "source": [
        "### Authenticate your GCP account\n",
        "\n",
        "**If you are using Google Cloud Notebooks**, your environment is already\n",
        "authenticated. Skip this step.\n",
        "\n",
        "*Note: If you are on an Vertex notebook and run the cell, the cell knows to skip executing the authentication steps.*\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MVoDIpoZRlv0"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import sys\n",
        "\n",
        "# If you are running this notebook in Colab, run this cell and follow the\n",
        "# instructions to authenticate your Google Cloud account. This provides access\n",
        "# to your Cloud Storage bucket and lets you submit training jobs and prediction\n",
        "# requests.\n",
        "\n",
        "# If on Vertex, then don't execute this code\n",
        "if not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
        "    if \"google.colab\" in sys.modules:\n",
        "        from google.colab import auth as google_auth\n",
        "\n",
        "        google_auth.authenticate_user()\n",
        "\n",
        "    # If you are running this tutorial in a notebook locally, replace the string\n",
        "    # below with the path to your service account key and run this cell to\n",
        "    # authenticate your Google Cloud account.\n",
        "    else:\n",
        "        %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json\n",
        "\n",
        "    # Log in to your account on Google Cloud\n",
        "    ! gcloud auth login"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bucket:batch_prediction"
      },
      "source": [
        "### Create a Cloud Storage bucket\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n",
        "\n",
        "Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bucket"
      },
      "outputs": [],
      "source": [
        "BUCKET_NAME = \"[your-bucket-name]\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "autoset_bucket"
      },
      "outputs": [],
      "source": [
        "if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
        "    BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "create_bucket"
      },
      "source": [
        "**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vIi5JxUcRlv3"
      },
      "outputs": [],
      "source": [
        "! gsutil mb -l $REGION gs://$BUCKET_NAME"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "validate_bucket"
      },
      "source": [
        "Finally, validate access to your Cloud Storage bucket by examining its contents:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "czQSbzsaRlv7"
      },
      "outputs": [],
      "source": [
        "! gsutil ls -al gs://$BUCKET_NAME"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "setup_vars"
      },
      "source": [
        "### Set up variables\n",
        "\n",
        "Next, set up some variables used throughout the tutorial.\n",
        "### Import libraries and define constants\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "import_aip"
      },
      "source": [
        "#### Import Vertex SDK\n",
        "\n",
        "Import the Vertex SDK into our Python environment.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-KblK5bSRlv8"
      },
      "outputs": [],
      "source": [
        "import json\n",
        "import os\n",
        "import sys\n",
        "import time\n",
        "from datetime import datetime\n",
        "\n",
        "from googleapiclient import discovery"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aip_constants"
      },
      "source": [
        "#### Vertex constants\n",
        "\n",
        "Setup up the following constants for Vertex:\n",
        "\n",
        "- `PARENT`: The Vertex location root path for dataset, model and endpoint resources.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "terGI8TzRlv9"
      },
      "outputs": [],
      "source": [
        "# Vertex location root path for your dataset, model and endpoint resources\n",
        "PARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "clients"
      },
      "source": [
        "## Clients\n",
        "\n",
        "The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).\n",
        "\n",
        "You will use several clients in this tutorial, so set them all up upfront.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2o-kpasCRlv-"
      },
      "outputs": [],
      "source": [
        "client = discovery.build(\"ml\", \"v1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rI2IQP-rRlv_"
      },
      "source": [
        "## Prepare a trainer script"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ldA8lSHtRlv_"
      },
      "source": [
        "### Package assembly"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5FT2-PifRlv_"
      },
      "outputs": [],
      "source": [
        "# Make folder for python training script\n",
        "! rm -rf custom\n",
        "! mkdir custom\n",
        "\n",
        "# Add package information\n",
        "! touch custom/README.md\n",
        "\n",
        "setup_cfg = \"[egg_info]\\n\\\n",
        "tag_build =\\n\\\n",
        "tag_date = 0\"\n",
        "! echo \"$setup_cfg\" > custom/setup.cfg\n",
        "\n",
        "setup_py = \"import setuptools\\n\\\n",
        "# Requires TensorFlow Datasets\\n\\\n",
        "setuptools.setup(\\n\\\n",
        "    install_requires=[\\n\\\n",
        "        'tensorflow_datasets==1.3.0',\\n\\\n",
        "    ],\\n\\\n",
        "    packages=setuptools.find_packages())\"\n",
        "! echo \"$setup_py\" > custom/setup.py\n",
        "\n",
        "pkg_info = \"Metadata-Version: 1.0\\n\\\n",
        "Name: Hyperparameter Tuning - Boston Housing\\n\\\n",
        "Version: 0.0.0\\n\\\n",
        "Summary: Demonstration hyperparameter tuning script\\n\\\n",
        "Home-page: www.google.com\\n\\\n",
        "Author: Google\\n\\\n",
        "Author-email: aferlitsch@gmail.com\\n\\\n",
        "License: Public\\n\\\n",
        "Description: Demo\\n\\\n",
        "Platform: Vertex AI\"\n",
        "! echo \"$pkg_info\" > custom/PKG-INFO\n",
        "\n",
        "# Make the training subfolder\n",
        "! mkdir custom/trainer\n",
        "! touch custom/trainer/__init__.py"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ogDv9tBORlv_"
      },
      "source": [
        "### Task.py contents"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0-Bj8SCcRlwA"
      },
      "outputs": [],
      "source": [
        "%%writefile custom/trainer/task.py\n",
        "# Custom Training for Boston Housing\n",
        "  \n",
        "import tensorflow_datasets as tfds\n",
        "import tensorflow as tf\n",
        "from tensorflow.python.client import device_lib\n",
        "from hypertune import HyperTune\n",
        "import numpy as np\n",
        "import argparse\n",
        "import os\n",
        "import sys\n",
        "tfds.disable_progress_bar()\n",
        "\n",
        "parser = argparse.ArgumentParser()\n",
        "parser.add_argument('--model-dir', dest='model_dir',\n",
        "                    default='/tmp/saved_model', type=str, help='Model dir.')\n",
        "parser.add_argument('--lr', dest='lr',\n",
        "                    default=0.001, type=float,\n",
        "                    help='Learning rate.')\n",
        "parser.add_argument('--units', dest='units',\n",
        "                    default=64, type=int,\n",
        "                    help='Number of units.')\n",
        "parser.add_argument('--epochs', dest='epochs',\n",
        "                    default=20, type=int,\n",
        "                    help='Number of epochs.')\n",
        "parser.add_argument('--param-file', dest='param_file',\n",
        "                    default='/tmp/param.txt', type=str,\n",
        "                    help='Output file for parameters')\n",
        "args = parser.parse_args()\n",
        "\n",
        "print('Python Version = {}'.format(sys.version))\n",
        "print('TensorFlow Version = {}'.format(tf.__version__))\n",
        "print('TF_CONFIG = {}'.format(os.environ.get('TF_CONFIG', 'Not found')))\n",
        "\n",
        "def make_dataset():\n",
        "  # Scaling Boston Housing data features\n",
        "  def scale(feature):\n",
        "    max = np.max(feature)\n",
        "    feature = (feature / max).astype(np.float)\n",
        "    return feature, max\n",
        "\n",
        "  (x_train, y_train), (x_test, y_test) = tf.keras.datasets.boston_housing.load_data(\n",
        "    path=\"boston_housing.npz\", test_split=0.2, seed=113\n",
        "  )\n",
        "  params = []\n",
        "  for _ in range(13):\n",
        "    x_train[_], max = scale(x_train[_])\n",
        "    x_test[_], _ = scale(x_test[_])\n",
        "    params.append(max)\n",
        "    \n",
        "  # store the normalization (max) value for each feature\n",
        "  with tf.io.gfile.GFile(args.param_file, 'w') as f:\n",
        "    f.write(str(params))\n",
        "  return (x_train, y_train), (x_test, y_test)\n",
        "\n",
        "# Build the Keras model\n",
        "def build_and_compile_dnn_model():\n",
        "  model = tf.keras.Sequential([\n",
        "      tf.keras.layers.Dense(args.units, activation='relu', input_shape=(13,)),\n",
        "      tf.keras.layers.Dense(args.units, activation='relu'),\n",
        "      tf.keras.layers.Dense(1, activation='linear')\n",
        "  ])\n",
        "  model.compile(\n",
        "      loss='mse',\n",
        "      optimizer=tf.keras.optimizers.RMSprop(learning_rate=args.lr))\n",
        "  return model\n",
        "\n",
        "model = build_and_compile_dnn_model()\n",
        "\n",
        "# Instantiate the HyperTune reporting object\n",
        "hpt = HyperTune()\n",
        "\n",
        "# Reporting callback\n",
        "class HPTCallback(tf.keras.callbacks.Callback):\n",
        "\n",
        "    def on_epoch_end(self, epoch, logs=None):\n",
        "        global hpt\n",
        "        hpt.report_hyperparameter_tuning_metric(\n",
        "        hyperparameter_metric_tag='val_loss',\n",
        "        metric_value=logs['val_loss'],\n",
        "        global_step=epoch)\n",
        "\n",
        "# Train the model\n",
        "BATCH_SIZE = 16\n",
        "(x_train, y_train), (x_test, y_test) = make_dataset()\n",
        "model.fit(x_train, y_train, epochs=args.epochs, batch_size=BATCH_SIZE, validation_split=0.1, callbacks=[HPTCallback()])\n",
        "model.save(args.model_dir)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "15pqExlERlwA"
      },
      "source": [
        "### Store training script on your Cloud Storage bucket"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YsuaEFZuRlwB"
      },
      "outputs": [],
      "source": [
        "! rm -f custom.tar custom.tar.gz\n",
        "! tar cvf custom.tar custom\n",
        "! gzip custom.tar\n",
        "! gsutil cp custom.tar.gz gs://$BUCKET_NAME/hpt_boston_housing.tar.gz"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "text_create_and_deploy_model:migration"
      },
      "source": [
        "## Train a model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0oqIBOSnJjkW"
      },
      "source": [
        "### [projects.jobs.create](https://cloud.google.com/ai-platform/training/docs/reference/rest/v1/projects.jobs/create)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TolZMkuSRlwC"
      },
      "source": [
        "#### Request"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bmSJIBU3RlwC"
      },
      "outputs": [],
      "source": [
        "JOB_NAME = \"hyperparameter_tuning_\" + TIMESTAMP\n",
        "\n",
        "training_input = {\n",
        "    \"scaleTier\": \"CUSTOM\",\n",
        "    \"masterType\": \"n1-standard-4\",\n",
        "    \"packageUris\": [\"gs://\" + BUCKET_NAME + \"/hpt_boston_housing.tar.gz\"],\n",
        "    \"pythonModule\": \"trainer.task\",\n",
        "    \"args\": [\n",
        "        \"--model-dir=\" + \"gs://{}/{}\".format(BUCKET_NAME, JOB_NAME),\n",
        "    ],\n",
        "    \"region\": REGION,\n",
        "    \"runtimeVersion\": \"2.1\",\n",
        "    \"pythonVersion\": \"3.7\",\n",
        "}\n",
        "\n",
        "# Add hyperparameter tuning to the job config.\n",
        "hyperparams = {\n",
        "    \"goal\": \"MINIMIZE\",\n",
        "    \"hyperparameterMetricTag\": \"val_loss\",\n",
        "    \"maxTrials\": 6,\n",
        "    \"maxParallelTrials\": 1,\n",
        "    \"params\": [],\n",
        "    \"algorithm\": \"RANDOM_SEARCH\",\n",
        "}\n",
        "\n",
        "hyperparams[\"params\"].append(\n",
        "    {\n",
        "        \"parameterName\": \"lr\",\n",
        "        \"type\": \"DISCRETE\",\n",
        "        \"discreteValues\": [0.001, 0.01, 0.1],\n",
        "        \"scaleType\": \"UNIT_LINEAR_SCALE\",\n",
        "    }\n",
        ")\n",
        "\n",
        "hyperparams[\"params\"].append(\n",
        "    {\n",
        "        \"parameterName\": \"units\",\n",
        "        \"type\": \"INTEGER\",\n",
        "        \"minValue\": 32,\n",
        "        \"maxValue\": 256,\n",
        "        \"scaleType\": \"UNIT_LINEAR_SCALE\",\n",
        "    }\n",
        ")\n",
        "\n",
        "# Add hyperparameter specification to the training inputs dictionary.\n",
        "training_input[\"hyperparameters\"] = hyperparams\n",
        "\n",
        "body = {\"jobId\": JOB_NAME, \"trainingInput\": training_input}\n",
        "\n",
        "request = (\n",
        "    client.projects()\n",
        "    .jobs()\n",
        "    .create(\n",
        "        parent=\"projects/\" + PROJECT_ID,\n",
        "    )\n",
        ")\n",
        "request.body = body\n",
        "\n",
        "print(json.dumps(json.loads(request.to_json()), indent=2))\n",
        "\n",
        "request = client.projects().jobs().create(parent=\"projects/\" + PROJECT_ID, body=body)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "datasets_import:migration,new,request"
      },
      "source": [
        "*Example output*:\n",
        "```\n",
        "{\n",
        "  \"uri\": \"https://ml.googleapis.com/v1/projects/migration-ucaip-training/jobs?alt=json\",\n",
        "  \"method\": \"POST\",\n",
        "  \"body\": {\n",
        "    \"jobId\": \"hyperparameter_tuning_20210226020553\",\n",
        "    \"trainingInput\": {\n",
        "      \"scaleTier\": \"CUSTOM\",\n",
        "      \"masterType\": \"n1-standard-4\",\n",
        "      \"packageUris\": [\n",
        "        \"gs://migration-ucaip-trainingaip-20210226020553/hpt_boston_housing.tar.gz\"\n",
        "      ],\n",
        "      \"pythonModule\": \"trainer.task\",\n",
        "      \"args\": [\n",
        "        \"--model-dir=gs://migration-ucaip-trainingaip-20210226020553/hyperparameter_tuning_20210226020553\"\n",
        "      ],\n",
        "      \"region\": \"us-central1\",\n",
        "      \"runtimeVersion\": \"2.1\",\n",
        "      \"pythonVersion\": \"3.7\",\n",
        "      \"hyperparameters\": {\n",
        "        \"goal\": \"MINIMIZE\",\n",
        "        \"hyperparameterMetricTag\": \"val_loss\",\n",
        "        \"maxTrials\": 6,\n",
        "        \"maxParallelTrials\": 1,\n",
        "        \"params\": [\n",
        "          {\n",
        "            \"parameterName\": \"lr\",\n",
        "            \"type\": \"DISCRETE\",\n",
        "            \"discreteValues\": [\n",
        "              0.001,\n",
        "              0.01,\n",
        "              0.1\n",
        "            ],\n",
        "            \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
        "          },\n",
        "          {\n",
        "            \"parameterName\": \"units\",\n",
        "            \"type\": \"INTEGER\",\n",
        "            \"minValue\": 32,\n",
        "            \"maxValue\": 256,\n",
        "            \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
        "          }\n",
        "        ],\n",
        "        \"algorithm\": \"RANDOM_SEARCH\"\n",
        "      }\n",
        "    }\n",
        "  },\n",
        "  \"headers\": {\n",
        "    \"accept\": \"application/json\",\n",
        "    \"accept-encoding\": \"gzip, deflate\",\n",
        "    \"user-agent\": \"(gzip)\",\n",
        "    \"x-goog-api-client\": \"gdcl/1.12.8 gl-python/3.7.8\"\n",
        "  },\n",
        "  \"methodId\": \"ml.projects.jobs.create\",\n",
        "  \"resumable\": null,\n",
        "  \"response_callbacks\": [],\n",
        "  \"_in_error_state\": false,\n",
        "  \"body_size\": 0,\n",
        "  \"resumable_uri\": null,\n",
        "  \"resumable_progress\": 0\n",
        "}\n",
        "```\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wC08Kt4eRlwE"
      },
      "source": [
        "#### Call"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yNWyRHq_RlwE"
      },
      "outputs": [],
      "source": [
        "result = request.execute()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rZZO8v7IRlwF"
      },
      "source": [
        "#### Response"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_dO8K_sDRlwF"
      },
      "outputs": [],
      "source": [
        "print(json.dumps(result, indent=2))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O85KoY2GRlwF"
      },
      "source": [
        "*Example output*:\n",
        "```\n",
        "{\n",
        "  \"jobId\": \"hyperparameter_tuning_20210226020553\",\n",
        "  \"trainingInput\": {\n",
        "    \"scaleTier\": \"CUSTOM\",\n",
        "    \"masterType\": \"n1-standard-4\",\n",
        "    \"packageUris\": [\n",
        "      \"gs://migration-ucaip-trainingaip-20210226020553/hpt_boston_housing.tar.gz\"\n",
        "    ],\n",
        "    \"pythonModule\": \"trainer.task\",\n",
        "    \"args\": [\n",
        "      \"--model-dir=gs://migration-ucaip-trainingaip-20210226020553/hyperparameter_tuning_20210226020553\"\n",
        "    ],\n",
        "    \"hyperparameters\": {\n",
        "      \"goal\": \"MINIMIZE\",\n",
        "      \"params\": [\n",
        "        {\n",
        "          \"parameterName\": \"lr\",\n",
        "          \"type\": \"DISCRETE\",\n",
        "          \"discreteValues\": [\n",
        "            0.001,\n",
        "            0.01,\n",
        "            0.1\n",
        "          ],\n",
        "          \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
        "        },\n",
        "        {\n",
        "          \"parameterName\": \"units\",\n",
        "          \"minValue\": 32,\n",
        "          \"maxValue\": 256,\n",
        "          \"type\": \"INTEGER\",\n",
        "          \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
        "        }\n",
        "      ],\n",
        "      \"maxTrials\": 6,\n",
        "      \"maxParallelTrials\": 1,\n",
        "      \"hyperparameterMetricTag\": \"val_loss\",\n",
        "      \"algorithm\": \"RANDOM_SEARCH\"\n",
        "    },\n",
        "    \"region\": \"us-central1\",\n",
        "    \"runtimeVersion\": \"2.1\",\n",
        "    \"pythonVersion\": \"3.7\"\n",
        "  },\n",
        "  \"createTime\": \"2021-02-26T02:06:01Z\",\n",
        "  \"state\": \"QUEUED\",\n",
        "  \"trainingOutput\": {\n",
        "    \"isHyperparameterTuningJob\": true\n",
        "  },\n",
        "  \"etag\": \"MPeWDTbQOUQ=\"\n",
        "}\n",
        "```\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "training_pipeline_id:migration,new,response"
      },
      "outputs": [],
      "source": [
        "# The short numeric ID for the custom training job\n",
        "hyperparameter_tuning_short_id = result[\"jobId\"]\n",
        "# The full unique ID for the custom training job\n",
        "hyperparameter_tuning_id = \"projects/\" + PROJECT_ID + \"/jobs/\" + result[\"jobId\"]\n",
        "\n",
        "print(hyperparameter_tuning_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PP31x5R4RlwG"
      },
      "source": [
        "### [projects.jobs.get](https://cloud.google.com/ai-platform/training/docs/reference/rest/v1/projects.jobs/get)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CNGyBG1iRlwG"
      },
      "source": [
        "#### Call"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mrlTlJw1RlwG"
      },
      "outputs": [],
      "source": [
        "request = client.projects().jobs().get(name=hyperparameter_tuning_id)\n",
        "\n",
        "result = request.execute()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dpGlbGq7RlwG"
      },
      "source": [
        "#### Response"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "00k1rWSORlwG"
      },
      "outputs": [],
      "source": [
        "print(json.dumps(result, indent=2))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KzcY5CWlRlwH"
      },
      "source": [
        "*Example output*:\n",
        "```\n",
        "{\n",
        "  \"jobId\": \"hyperparameter_tuning_20210226020553\",\n",
        "  \"trainingInput\": {\n",
        "    \"scaleTier\": \"CUSTOM\",\n",
        "    \"masterType\": \"n1-standard-4\",\n",
        "    \"packageUris\": [\n",
        "      \"gs://migration-ucaip-trainingaip-20210226020553/hpt_boston_housing.tar.gz\"\n",
        "    ],\n",
        "    \"pythonModule\": \"trainer.task\",\n",
        "    \"args\": [\n",
        "      \"--model-dir=gs://migration-ucaip-trainingaip-20210226020553/hyperparameter_tuning_20210226020553\"\n",
        "    ],\n",
        "    \"hyperparameters\": {\n",
        "      \"goal\": \"MINIMIZE\",\n",
        "      \"params\": [\n",
        "        {\n",
        "          \"parameterName\": \"lr\",\n",
        "          \"type\": \"DISCRETE\",\n",
        "          \"discreteValues\": [\n",
        "            0.001,\n",
        "            0.01,\n",
        "            0.1\n",
        "          ],\n",
        "          \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
        "        },\n",
        "        {\n",
        "          \"parameterName\": \"units\",\n",
        "          \"minValue\": 32,\n",
        "          \"maxValue\": 256,\n",
        "          \"type\": \"INTEGER\",\n",
        "          \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
        "        }\n",
        "      ],\n",
        "      \"maxTrials\": 6,\n",
        "      \"maxParallelTrials\": 1,\n",
        "      \"hyperparameterMetricTag\": \"val_loss\",\n",
        "      \"algorithm\": \"RANDOM_SEARCH\"\n",
        "    },\n",
        "    \"region\": \"us-central1\",\n",
        "    \"runtimeVersion\": \"2.1\",\n",
        "    \"pythonVersion\": \"3.7\"\n",
        "  },\n",
        "  \"createTime\": \"2021-02-26T02:06:01Z\",\n",
        "  \"state\": \"QUEUED\",\n",
        "  \"trainingOutput\": {\n",
        "    \"isHyperparameterTuningJob\": true\n",
        "  },\n",
        "  \"etag\": \"GNEDjq+ds8I=\"\n",
        "}\n",
        "```\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LWe8jWSTRlwH"
      },
      "source": [
        "## Wait for the study to complete"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "trainingpipelines_get:migration,new,wait"
      },
      "outputs": [],
      "source": [
        "while True:\n",
        "    response = client.projects().jobs().get(name=hyperparameter_tuning_id).execute()\n",
        "\n",
        "    if response[\"state\"] != \"SUCCEEDED\":\n",
        "        print(\"Study trials have not completed:\", response[\"state\"])\n",
        "        if response[\"state\"] == \"FAILED\":\n",
        "            break\n",
        "    else:\n",
        "        print(\"Study trials have completed:\")\n",
        "        break\n",
        "    time.sleep(60)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cGHPc83JRlwH"
      },
      "outputs": [],
      "source": [
        "print(json.dumps(response, indent=2))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B5x1sVCCRlwI"
      },
      "source": [
        "*Example output*:\n",
        "```\n",
        "{\n",
        "  \"jobId\": \"hyperparameter_tuning_20210226020553\",\n",
        "  \"trainingInput\": {\n",
        "    \"scaleTier\": \"CUSTOM\",\n",
        "    \"masterType\": \"n1-standard-4\",\n",
        "    \"packageUris\": [\n",
        "      \"gs://migration-ucaip-trainingaip-20210226020553/hpt_boston_housing.tar.gz\"\n",
        "    ],\n",
        "    \"pythonModule\": \"trainer.task\",\n",
        "    \"args\": [\n",
        "      \"--model-dir=gs://migration-ucaip-trainingaip-20210226020553/hyperparameter_tuning_20210226020553\"\n",
        "    ],\n",
        "    \"hyperparameters\": {\n",
        "      \"goal\": \"MINIMIZE\",\n",
        "      \"params\": [\n",
        "        {\n",
        "          \"parameterName\": \"lr\",\n",
        "          \"type\": \"DISCRETE\",\n",
        "          \"discreteValues\": [\n",
        "            0.001,\n",
        "            0.01,\n",
        "            0.1\n",
        "          ],\n",
        "          \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
        "        },\n",
        "        {\n",
        "          \"parameterName\": \"units\",\n",
        "          \"minValue\": 32,\n",
        "          \"maxValue\": 256,\n",
        "          \"type\": \"INTEGER\",\n",
        "          \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
        "        }\n",
        "      ],\n",
        "      \"maxTrials\": 6,\n",
        "      \"maxParallelTrials\": 1,\n",
        "      \"hyperparameterMetricTag\": \"val_loss\",\n",
        "      \"algorithm\": \"RANDOM_SEARCH\"\n",
        "    },\n",
        "    \"region\": \"us-central1\",\n",
        "    \"runtimeVersion\": \"2.1\",\n",
        "    \"pythonVersion\": \"3.7\"\n",
        "  },\n",
        "  \"createTime\": \"2021-02-26T02:06:01Z\",\n",
        "  \"startTime\": \"2021-02-26T02:06:03Z\",\n",
        "  \"endTime\": \"2021-02-26T02:35:25Z\",\n",
        "  \"state\": \"SUCCEEDED\",\n",
        "  \"trainingOutput\": {\n",
        "    \"completedTrialCount\": \"6\",\n",
        "    \"trials\": [\n",
        "      {\n",
        "        \"trialId\": \"3\",\n",
        "        \"hyperparameters\": {\n",
        "          \"lr\": \"0.1\",\n",
        "          \"units\": \"39\"\n",
        "        },\n",
        "        \"finalMetric\": {\n",
        "          \"trainingStep\": \"8\",\n",
        "          \"objectiveValue\": 45.76672372585389\n",
        "        },\n",
        "        \"startTime\": \"2021-02-26T02:16:50.943369954Z\",\n",
        "        \"endTime\": \"2021-02-26T02:20:15Z\",\n",
        "        \"state\": \"SUCCEEDED\"\n",
        "      },\n",
        "      {\n",
        "        \"trialId\": \"5\",\n",
        "        \"hyperparameters\": {\n",
        "          \"lr\": \"0.1\",\n",
        "          \"units\": \"169\"\n",
        "        },\n",
        "        \"finalMetric\": {\n",
        "          \"trainingStep\": \"19\",\n",
        "          \"objectiveValue\": 46.09460951642292\n",
        "        },\n",
        "        \"startTime\": \"2021-02-26T02:26:23.876101420Z\",\n",
        "        \"endTime\": \"2021-02-26T02:29:59Z\",\n",
        "        \"state\": \"SUCCEEDED\"\n",
        "      },\n",
        "      {\n",
        "        \"trialId\": \"2\",\n",
        "        \"hyperparameters\": {\n",
        "          \"lr\": \"0.1\",\n",
        "          \"units\": \"69\"\n",
        "        },\n",
        "        \"finalMetric\": {\n",
        "          \"trainingStep\": \"19\",\n",
        "          \"objectiveValue\": 51.7642993461795\n",
        "        },\n",
        "        \"startTime\": \"2021-02-26T02:12:03.812631906Z\",\n",
        "        \"endTime\": \"2021-02-26T02:15:30Z\",\n",
        "        \"state\": \"SUCCEEDED\"\n",
        "      },\n",
        "      {\n",
        "        \"trialId\": \"1\",\n",
        "        \"hyperparameters\": {\n",
        "          \"lr\": \"0.01\",\n",
        "          \"units\": \"232\"\n",
        "        },\n",
        "        \"finalMetric\": {\n",
        "          \"trainingStep\": \"19\",\n",
        "          \"objectiveValue\": 55.58717541578339\n",
        "        },\n",
        "        \"startTime\": \"2021-02-26T02:06:40.790962827Z\",\n",
        "        \"endTime\": \"2021-02-26T02:10:47Z\",\n",
        "        \"state\": \"SUCCEEDED\"\n",
        "      },\n",
        "      {\n",
        "        \"trialId\": \"6\",\n",
        "        \"hyperparameters\": {\n",
        "          \"lr\": \"0.001\",\n",
        "          \"units\": \"123\"\n",
        "        },\n",
        "        \"finalMetric\": {\n",
        "          \"trainingStep\": \"19\",\n",
        "          \"objectiveValue\": 76.20946111911681\n",
        "        },\n",
        "        \"startTime\": \"2021-02-26T02:31:11.163541810Z\",\n",
        "        \"endTime\": \"2021-02-26T02:34:36Z\",\n",
        "        \"state\": \"SUCCEEDED\"\n",
        "      },\n",
        "      {\n",
        "        \"trialId\": \"4\",\n",
        "        \"hyperparameters\": {\n",
        "          \"lr\": \"0.01\",\n",
        "          \"units\": \"246\"\n",
        "        },\n",
        "        \"finalMetric\": {\n",
        "          \"trainingStep\": \"11\",\n",
        "          \"objectiveValue\": 100.75884600383479\n",
        "        },\n",
        "        \"startTime\": \"2021-02-26T02:21:36.635969861Z\",\n",
        "        \"endTime\": \"2021-02-26T02:25:02Z\",\n",
        "        \"state\": \"SUCCEEDED\"\n",
        "      }\n",
        "    ],\n",
        "    \"consumedMLUnits\": 0.39,\n",
        "    \"isHyperparameterTuningJob\": true,\n",
        "    \"hyperparameterMetricTag\": \"val_loss\"\n",
        "  },\n",
        "  \"etag\": \"eUgnylIe/+0=\"\n",
        "}\n",
        "```\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1WqbO9gSRlwI"
      },
      "source": [
        "## Review the results of the study"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "X0ooazLvRlwI"
      },
      "outputs": [],
      "source": [
        "best = (None, None, None, 0.0)\n",
        "response = client.projects().jobs().get(name=hyperparameter_tuning_id).execute()\n",
        "for trial in response[\"trainingOutput\"][\"trials\"]:\n",
        "    print(json.dumps(trial, indent=2))\n",
        "    # Keep track of the best outcome\n",
        "    try:\n",
        "        if float(trial.final_measurement.metrics[0].value) > best[3]:\n",
        "            best = (\n",
        "                trial.id,\n",
        "                float(trial.parameters[0].value),\n",
        "                float(trial.parameters[1].value),\n",
        "                float(trial.final_measurement.metrics[0].value),\n",
        "            )\n",
        "    except:\n",
        "        pass\n",
        "\n",
        "print()\n",
        "print(\"ID\", best[0])\n",
        "print(\"Decay\", best[1])\n",
        "print(\"Learning Rate\", best[2])\n",
        "print(\"Validation Accuracy\", best[3])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l4nWUlSIRlwI"
      },
      "source": [
        "*Example output*:\n",
        "```\n",
        "{\n",
        "  \"trialId\": \"3\",\n",
        "  \"hyperparameters\": {\n",
        "    \"lr\": \"0.1\",\n",
        "    \"units\": \"39\"\n",
        "  },\n",
        "  \"finalMetric\": {\n",
        "    \"trainingStep\": \"8\",\n",
        "    \"objectiveValue\": 45.76672372585389\n",
        "  },\n",
        "  \"startTime\": \"2021-02-26T02:16:50.943369954Z\",\n",
        "  \"endTime\": \"2021-02-26T02:20:15Z\",\n",
        "  \"state\": \"SUCCEEDED\"\n",
        "}\n",
        "{\n",
        "  \"trialId\": \"5\",\n",
        "  \"hyperparameters\": {\n",
        "    \"lr\": \"0.1\",\n",
        "    \"units\": \"169\"\n",
        "  },\n",
        "  \"finalMetric\": {\n",
        "    \"trainingStep\": \"19\",\n",
        "    \"objectiveValue\": 46.09460951642292\n",
        "  },\n",
        "  \"startTime\": \"2021-02-26T02:26:23.876101420Z\",\n",
        "  \"endTime\": \"2021-02-26T02:29:59Z\",\n",
        "  \"state\": \"SUCCEEDED\"\n",
        "}\n",
        "{\n",
        "  \"trialId\": \"2\",\n",
        "  \"hyperparameters\": {\n",
        "    \"lr\": \"0.1\",\n",
        "    \"units\": \"69\"\n",
        "  },\n",
        "  \"finalMetric\": {\n",
        "    \"trainingStep\": \"19\",\n",
        "    \"objectiveValue\": 51.7642993461795\n",
        "  },\n",
        "  \"startTime\": \"2021-02-26T02:12:03.812631906Z\",\n",
        "  \"endTime\": \"2021-02-26T02:15:30Z\",\n",
        "  \"state\": \"SUCCEEDED\"\n",
        "}\n",
        "{\n",
        "  \"trialId\": \"1\",\n",
        "  \"hyperparameters\": {\n",
        "    \"lr\": \"0.01\",\n",
        "    \"units\": \"232\"\n",
        "  },\n",
        "  \"finalMetric\": {\n",
        "    \"trainingStep\": \"19\",\n",
        "    \"objectiveValue\": 55.58717541578339\n",
        "  },\n",
        "  \"startTime\": \"2021-02-26T02:06:40.790962827Z\",\n",
        "  \"endTime\": \"2021-02-26T02:10:47Z\",\n",
        "  \"state\": \"SUCCEEDED\"\n",
        "}\n",
        "{\n",
        "  \"trialId\": \"6\",\n",
        "  \"hyperparameters\": {\n",
        "    \"lr\": \"0.001\",\n",
        "    \"units\": \"123\"\n",
        "  },\n",
        "  \"finalMetric\": {\n",
        "    \"trainingStep\": \"19\",\n",
        "    \"objectiveValue\": 76.20946111911681\n",
        "  },\n",
        "  \"startTime\": \"2021-02-26T02:31:11.163541810Z\",\n",
        "  \"endTime\": \"2021-02-26T02:34:36Z\",\n",
        "  \"state\": \"SUCCEEDED\"\n",
        "}\n",
        "{\n",
        "  \"trialId\": \"4\",\n",
        "  \"hyperparameters\": {\n",
        "    \"lr\": \"0.01\",\n",
        "    \"units\": \"246\"\n",
        "  },\n",
        "  \"finalMetric\": {\n",
        "    \"trainingStep\": \"11\",\n",
        "    \"objectiveValue\": 100.75884600383479\n",
        "  },\n",
        "  \"startTime\": \"2021-02-26T02:21:36.635969861Z\",\n",
        "  \"endTime\": \"2021-02-26T02:25:02Z\",\n",
        "  \"state\": \"SUCCEEDED\"\n",
        "}\n",
        "\n",
        "ID None\n",
        "Decay None\n",
        "Learning Rate None\n",
        "Validation Accuracy 0.0\n",
        "```\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cleanup:migration,new"
      },
      "source": [
        "# Cleaning up\n",
        "\n",
        "To clean up all GCP resources used in this project, you can [delete the GCP\n",
        "project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
        "\n",
        "Otherwise, you can delete the individual resources you created in this tutorial.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fyVK3PbnRlwJ"
      },
      "outputs": [],
      "source": [
        "delete_bucket = True\n",
        "\n",
        "if delete_bucket and \"BUCKET_NAME\" in globals():\n",
        "    ! gsutil rm -r gs://$BUCKET_NAME"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "import_aip",
        "aip_constants",
        "TolZMkuSRlwC",
        "wC08Kt4eRlwE",
        "rZZO8v7IRlwF",
        "CNGyBG1iRlwG",
        "dpGlbGq7RlwG"
      ],
      "name": "UJ11 legacy HyperParameter Tuning Training Job with TensorFlow.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
